<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/atom.xml" title="liujinlongxa的技术博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言前一篇介绍了iOS7新出的TextKit，这一篇打算介绍一下更底层的CoreText框架
简介CoreText是iOS3.2推出的一套文字排版和渲染框架，可以实现图文混排，富文本显示等效果。CoreText中的几个重要的概念：

CTFrameRef：画布，包含多个CTLine
CTLineRef：每一行就是一个CTLine
CTRunRef：每一行可以分为多个属性相同的小段，每一个小段就是一">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS中的富文本技术(2)CoreText框架">
<meta property="og:url" content="http://yoursite.com/2015/10/04/iOS中的富文本技术(2)CoreText框架/index.html">
<meta property="og:site_name" content="liujinlongxa的技术博客">
<meta property="og:description" content="前言前一篇介绍了iOS7新出的TextKit，这一篇打算介绍一下更底层的CoreText框架
简介CoreText是iOS3.2推出的一套文字排版和渲染框架，可以实现图文混排，富文本显示等效果。CoreText中的几个重要的概念：

CTFrameRef：画布，包含多个CTLine
CTLineRef：每一行就是一个CTLine
CTRunRef：每一行可以分为多个属性相同的小段，每一个小段就是一">
<meta property="og:image" content="http://img.blog.csdn.net/20150403235844681">
<meta property="og:image" content="http://img.blog.csdn.net/20150404001114995">
<meta property="og:image" content="http://img.blog.csdn.net/20150404002937477">
<meta property="og:updated_time" content="2016-07-01T12:43:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS中的富文本技术(2)CoreText框架">
<meta name="twitter:description" content="前言前一篇介绍了iOS7新出的TextKit，这一篇打算介绍一下更底层的CoreText框架
简介CoreText是iOS3.2推出的一套文字排版和渲染框架，可以实现图文混排，富文本显示等效果。CoreText中的几个重要的概念：

CTFrameRef：画布，包含多个CTLine
CTLineRef：每一行就是一个CTLine
CTRunRef：每一行可以分为多个属性相同的小段，每一个小段就是一">
<meta name="twitter:image" content="http://img.blog.csdn.net/20150403235844681">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2015/10/04/iOS中的富文本技术(2)CoreText框架/"/>

  <title> iOS中的富文本技术(2)CoreText框架 | liujinlongxa的技术博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">liujinlongxa的技术博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                iOS中的富文本技术(2)CoreText框架
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2015-10-04T00:00:00+08:00" content="2015-10-04">
              2015-10-04
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/iOS开发/" itemprop="url" rel="index">
                    <span itemprop="name">iOS开发</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2015/10/04/iOS中的富文本技术(2)CoreText框架/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2015/10/04/iOS中的富文本技术(2)CoreText框架/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>前一篇介绍了iOS7新出的TextKit，这一篇打算介绍一下更底层的CoreText框架</p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>CoreText是iOS3.2推出的一套文字排版和渲染框架，可以实现图文混排，富文本显示等效果。CoreText中的几个重要的概念：</p>
<ul>
<li>CTFrameRef：画布，包含多个CTLine</li>
<li>CTLineRef：每一行就是一个CTLine</li>
<li>CTRunRef：每一行可以分为多个属性相同的小段，每一个小段就是一个CTRun<br>如下图展示了这三者的关系：</li>
</ul>
<p><img src="http://img.blog.csdn.net/20150403235844681" alt="这里写图片描述"></p>
<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><p>废话不多说，直接看示例，第一个示例展示了一些常规属性的的设置，效果图如下：</p>
<p><img src="http://img.blog.csdn.net/20150404001114995" alt="这里写图片描述"></p>
<p>代码如下，这里使用了一个自定义View，然后把要展示的内容绘制在view上，注意代码中使用了很多CoreFoundation框架的类（实际上是结构体），需要使用__bridge进行桥接：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"DisplayView.h"</span></span></div><div class="line"><span class="keyword">@import</span> CoreText;</div><div class="line"></div><div class="line"><span class="built_in">NSString</span> * str4 = <span class="string">@"asfasfa阿斯顿发生大发撒放大离开家撒旦法按时付款就阿里；双方均asfasdfasfdalkjsflakj阿斯顿发生大发撒旦法asdfasdfaasfdaasa撒旦法；拉斯克奖发了奥斯卡奖罚洛杉矶的法律；看见谁发的阿斯利康就发；了数据库等法律按实际开发；阿里就开始放到了；安家费阿里山科技发达了开始将对方拉开始交电费了卡双方的空间啊发送卡飞机阿里开始就放暑假了罚款就是浪费"</span>;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">DisplayView</span> ()</span></div><div class="line"></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">DisplayView</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)drawRect:(<span class="built_in">CGRect</span>)rect &#123;</div><div class="line"></div><div class="line">    [<span class="keyword">super</span> drawRect:rect];</div><div class="line"></div><div class="line">    <span class="built_in">CGContextRef</span> context = <span class="built_in">UIGraphicsGetCurrentContext</span>();</div><div class="line"></div><div class="line">    <span class="comment">//变换坐标</span></div><div class="line">    <span class="built_in">CGContextSetTextMatrix</span>(context, <span class="built_in">CGAffineTransformIdentity</span>);</div><div class="line">    <span class="built_in">CGContextTranslateCTM</span>(context, <span class="number">0</span>, <span class="keyword">self</span>.bounds.size.height);</div><div class="line">    <span class="built_in">CGContextScaleCTM</span>(context, <span class="number">1.0</span>, <span class="number">-1.0</span>);</div><div class="line"></div><div class="line">    <span class="comment">//设置绘制的路径</span></div><div class="line">    <span class="built_in">CGMutablePathRef</span> path = <span class="built_in">CGPathCreateMutable</span>();</div><div class="line">    <span class="built_in">CGPathAddRect</span>(path, <span class="literal">NULL</span>, <span class="keyword">self</span>.bounds);</div><div class="line"></div><div class="line">    <span class="comment">//创建属性字符串</span></div><div class="line">    <span class="built_in">NSMutableAttributedString</span> * attStr = [[<span class="built_in">NSMutableAttributedString</span> alloc] initWithString:str4];</div><div class="line"></div><div class="line">    <span class="comment">//颜色</span></div><div class="line">    [attStr addAttribute:(__bridge <span class="built_in">NSString</span> *)kCTForegroundColorAttributeName value:(__bridge <span class="keyword">id</span>)[<span class="built_in">UIColor</span> redColor].CGColor range:<span class="built_in">NSMakeRange</span>(<span class="number">5</span>, <span class="number">10</span>)];</div><div class="line"></div><div class="line">    <span class="comment">//字体</span></div><div class="line">    <span class="built_in">UIFont</span> * font = [<span class="built_in">UIFont</span> systemFontOfSize:<span class="number">25</span>];</div><div class="line">    <span class="built_in">CTFontRef</span> fontRef = <span class="built_in">CTFontCreateWithName</span>((__bridge <span class="built_in">CFStringRef</span>)font.fontName, <span class="number">25</span>, <span class="literal">NULL</span>);</div><div class="line">    [attStr addAttribute:(__bridge <span class="built_in">NSString</span> *)kCTFontAttributeName value:(__bridge <span class="keyword">id</span>)fontRef range:<span class="built_in">NSMakeRange</span>(<span class="number">20</span>, <span class="number">10</span>)];</div><div class="line"></div><div class="line">    <span class="comment">//空心字</span></div><div class="line">    [attStr addAttribute:(__bridge <span class="built_in">NSString</span> *)kCTStrokeWidthAttributeName value:@(<span class="number">3</span>) range:<span class="built_in">NSMakeRange</span>(<span class="number">36</span>, <span class="number">5</span>)];</div><div class="line">    [attStr addAttribute:(__bridge <span class="built_in">NSString</span> *)kCTStrokeColorAttributeName value:(__bridge <span class="keyword">id</span>)[<span class="built_in">UIColor</span> blueColor].CGColor range:<span class="built_in">NSMakeRange</span>(<span class="number">37</span>, <span class="number">10</span>)];</div><div class="line"></div><div class="line">    <span class="comment">//下划线</span></div><div class="line">    [attStr addAttribute:(__bridge <span class="built_in">NSString</span> *)kCTUnderlineStyleAttributeName value:@(kCTUnderlineStyleSingle | kCTUnderlinePatternDot) range:<span class="built_in">NSMakeRange</span>(<span class="number">45</span>, <span class="number">15</span>)];</div><div class="line"></div><div class="line"></div><div class="line">    <span class="built_in">CTFramesetterRef</span> framesetter = <span class="built_in">CTFramesetterCreateWithAttributedString</span>((<span class="built_in">CFAttributedStringRef</span>)attStr);</div><div class="line">    <span class="built_in">CTFrameRef</span> frame = <span class="built_in">CTFramesetterCreateFrame</span>(framesetter, <span class="built_in">CFRangeMake</span>(<span class="number">0</span>, attStr.length), path, <span class="literal">NULL</span>);</div><div class="line"></div><div class="line">    <span class="comment">//绘制内容</span></div><div class="line">    <span class="built_in">CTFrameDraw</span>(frame, context);</div><div class="line"></div><div class="line">    <span class="built_in">CFRelease</span>(fontRef);</div><div class="line">    <span class="built_in">CFRelease</span>(frame);</div><div class="line">    <span class="built_in">CFRelease</span>(path);</div><div class="line">    <span class="built_in">CFRelease</span>(framesetter);</div><div class="line"></div><div class="line">&#125;</div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<p>第二个示例展示了一个带表情符号的文本，效果图如下：</p>
<p><img src="http://img.blog.csdn.net/20150404002937477" alt="这里写图片描述"></p>
<p>先介绍一下CoreText实现表情混排的原理，在简介中介绍过，一个CTLine代表一行，而一个CTLine又由多个CTRun组成，这里实现表情混排的原理其实就是把CTLine中的某一个CTRun替换成空白字符，然后再根据这个CTRun的具体位置，把图片绘制到这个位置上，下面是具体代码：<br><figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"ImageDisplayView.h"</span></span></div><div class="line"><span class="keyword">@import</span> CoreText;</div><div class="line"></div><div class="line"><span class="built_in">NSString</span> * str5 = <span class="string">@"asfasfa阿斯顿发生大发撒放大离开家撒旦法按时付款就阿里；双方均asfasdfasfdalkjsflakj阿斯顿发生大发撒旦法asdfasdfaasfdaasa撒旦法；拉斯克奖发了奥斯卡奖罚洛杉矶的法律；看见谁发的阿斯利康就发；了数据库等法律按实际开发；阿里就开始放到了；安家费阿里山科技发达了开始将对方拉开始交电费了卡双方的空间啊发送卡飞机阿里开始就放暑假了罚款就是浪费"</span>;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">ImageDisplayView</span> ()</span></div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) <span class="built_in">NSAttributedString</span> * attStr;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div><div class="line"></div><div class="line"><span class="comment">//回调方法，返回要替换的CTRun的下边缘距离本行文字下边缘的高度</span></div><div class="line"><span class="keyword">static</span> <span class="built_in">CGFloat</span> descentCallback(<span class="keyword">void</span> *ref)</div><div class="line">&#123;</div><div class="line">    <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//回调方法，返回要替换的CTRun的上边缘距离本行文字上边缘的高度</span></div><div class="line"><span class="keyword">static</span> <span class="built_in">CGFloat</span> ascentCallback(<span class="keyword">void</span> *ref)</div><div class="line">&#123;</div><div class="line">    <span class="keyword">return</span> <span class="number">30</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//回调方法，返回要替换的CTRun的宽</span></div><div class="line"><span class="keyword">static</span> <span class="built_in">CGFloat</span> widthCallback(<span class="keyword">void</span> *ref)</div><div class="line">&#123;</div><div class="line">    <span class="keyword">return</span> <span class="number">30</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">ImageDisplayView</span></span></div><div class="line">&#123;</div><div class="line">    <span class="built_in">CTRunDelegateRef</span> _delegate;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">instancetype</span>)initWithFrame:(<span class="built_in">CGRect</span>)frame</div><div class="line">&#123;</div><div class="line">    <span class="keyword">self</span> = [<span class="keyword">super</span> initWithFrame:frame];</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">self</span>) &#123;</div><div class="line">        <span class="built_in">NSString</span> * name = <span class="string">@"010"</span>;</div><div class="line">        <span class="keyword">unichar</span> objectReplacementChar           = <span class="number">0xFFFC</span>;<span class="comment">//占位字符</span></div><div class="line">        <span class="built_in">NSString</span> *objectReplacementString       = [<span class="built_in">NSString</span> stringWithCharacters:&amp;objectReplacementChar length:<span class="number">1</span>];</div><div class="line">        <span class="built_in">NSMutableAttributedString</span> *attachText   = [[<span class="built_in">NSMutableAttributedString</span> alloc]initWithString:objectReplacementString];</div><div class="line"></div><div class="line">        <span class="comment">//创建CTRun代理回调</span></div><div class="line">        <span class="built_in">CTRunDelegateCallbacks</span> callbacks;</div><div class="line">        callbacks.version       = kCTRunDelegateVersion1;</div><div class="line">        callbacks.getAscent     = ascentCallback;</div><div class="line">        callbacks.getDescent    = descentCallback;</div><div class="line">        callbacks.getWidth      = widthCallback;</div><div class="line"></div><div class="line">        <span class="comment">//给属性字符串添加代理回调</span></div><div class="line">        <span class="built_in">CTRunDelegateRef</span> delegate = <span class="built_in">CTRunDelegateCreate</span>(&amp;callbacks, (<span class="keyword">void</span> *)name);</div><div class="line">        <span class="built_in">NSDictionary</span> *attr = [<span class="built_in">NSDictionary</span> dictionaryWithObjectsAndKeys:(__bridge <span class="keyword">id</span>)delegate,kCTRunDelegateAttributeName, <span class="literal">nil</span>];</div><div class="line">        [attachText setAttributes:attr range:<span class="built_in">NSMakeRange</span>(<span class="number">0</span>, <span class="number">1</span>)];</div><div class="line">        <span class="keyword">self</span>.attStr = attachText;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="keyword">void</span>)drawRect:(<span class="built_in">CGRect</span>)rect &#123;</div><div class="line"></div><div class="line">    [<span class="keyword">super</span> drawRect:rect];</div><div class="line"></div><div class="line">    <span class="built_in">CGContextRef</span> context = <span class="built_in">UIGraphicsGetCurrentContext</span>();</div><div class="line"></div><div class="line">    <span class="comment">//变换坐标</span></div><div class="line">    <span class="built_in">CGContextSetTextMatrix</span>(context, <span class="built_in">CGAffineTransformIdentity</span>);</div><div class="line">    <span class="built_in">CGContextTranslateCTM</span>(context, <span class="number">0</span>, <span class="keyword">self</span>.bounds.size.height);</div><div class="line">    <span class="built_in">CGContextScaleCTM</span>(context, <span class="number">1.0</span>, <span class="number">-1.0</span>);</div><div class="line"></div><div class="line">    <span class="comment">//设置文本绘制的路径</span></div><div class="line">    <span class="built_in">CGMutablePathRef</span> path = <span class="built_in">CGPathCreateMutable</span>();</div><div class="line">    <span class="built_in">CGPathAddRect</span>(path, <span class="literal">NULL</span>, <span class="keyword">self</span>.bounds);</div><div class="line"></div><div class="line">    <span class="built_in">NSMutableAttributedString</span> * attStr = [[<span class="built_in">NSMutableAttributedString</span> alloc] initWithString:str5];</div><div class="line">    [attStr insertAttributedString:<span class="keyword">self</span>.attStr atIndex:<span class="number">50</span>];</div><div class="line"></div><div class="line">    <span class="built_in">CTFramesetterRef</span> framesetter = <span class="built_in">CTFramesetterCreateWithAttributedString</span>((<span class="built_in">CFAttributedStringRef</span>)attStr);</div><div class="line">    <span class="built_in">CTFrameRef</span> frame = <span class="built_in">CTFramesetterCreateFrame</span>(framesetter, <span class="built_in">CFRangeMake</span>(<span class="number">0</span>, attStr.length), path, <span class="literal">NULL</span>);</div><div class="line"></div><div class="line">    <span class="comment">//计算要替换的CTRun的具体位置</span></div><div class="line">    <span class="built_in">NSArray</span> * lines = (<span class="built_in">NSArray</span> *)<span class="built_in">CTFrameGetLines</span>(frame);</div><div class="line">    <span class="built_in">NSUInteger</span> lineCount = lines.count;</div><div class="line">    <span class="built_in">CGPoint</span> lineOrigins[lineCount];</div><div class="line">    <span class="built_in">CTFrameGetLineOrigins</span>(frame, <span class="built_in">CFRangeMake</span>(<span class="number">0</span>, <span class="number">0</span>), lineOrigins);</div><div class="line">    <span class="comment">//循环遍历每一个CTLine中的每一个CTRun，找到要替换的那个CTRun，并且计算它的位置</span></div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; lineCount; i++) &#123;</div><div class="line">        <span class="built_in">CTLineRef</span> line = (__bridge <span class="built_in">CTLineRef</span>)lines[i];</div><div class="line">        <span class="built_in">CFArrayRef</span> runs = <span class="built_in">CTLineGetGlyphRuns</span>(line);</div><div class="line">        <span class="built_in">CFIndex</span> runCount = <span class="built_in">CFArrayGetCount</span>(runs);</div><div class="line">        <span class="built_in">CGPoint</span> lineOrigin = lineOrigins[i];</div><div class="line">        <span class="built_in">CGFloat</span> lineAscent;</div><div class="line">        <span class="built_in">CGFloat</span> lineDescent;</div><div class="line">        <span class="built_in">CTLineGetTypographicBounds</span>(line, &amp;lineAscent, &amp;lineDescent, <span class="literal">NULL</span>);</div><div class="line">        <span class="keyword">for</span> (<span class="built_in">CFIndex</span> k = <span class="number">0</span>; k &lt; runCount; k++)</div><div class="line">        &#123;</div><div class="line">            <span class="built_in">CTRunRef</span> run = <span class="built_in">CFArrayGetValueAtIndex</span>(runs, k);</div><div class="line">            <span class="built_in">NSDictionary</span> *runAttributes = (<span class="built_in">NSDictionary</span> *)<span class="built_in">CTRunGetAttributes</span>(run);</div><div class="line">            <span class="built_in">CTRunDelegateRef</span> delegate = (__bridge <span class="built_in">CTRunDelegateRef</span>)[runAttributes valueForKey:(<span class="keyword">id</span>)kCTRunDelegateAttributeName];</div><div class="line">            <span class="keyword">if</span> (<span class="literal">nil</span> == delegate)</div><div class="line">            &#123;</div><div class="line">                <span class="keyword">continue</span>;</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            <span class="built_in">CGFloat</span> xOffset = <span class="built_in">CTLineGetOffsetForStringIndex</span>(line, <span class="built_in">CTRunGetStringRange</span>(run).location, <span class="literal">nil</span>);</div><div class="line">            <span class="built_in">CGRect</span> rect = <span class="built_in">CGRectMake</span>(lineOrigin.x + xOffset, lineOrigin.y - lineDescent, <span class="number">30</span>, <span class="number">30</span>);</div><div class="line"></div><div class="line">            <span class="comment">//绘制图片</span></div><div class="line">            <span class="built_in">CGContextDrawImage</span>(context, rect, [<span class="built_in">UIImage</span> imageNamed:<span class="string">@"010"</span>].CGImage);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="built_in">CTFrameDraw</span>(frame, context);</div><div class="line"></div><div class="line">    <span class="built_in">CFRelease</span>(frame);</div><div class="line">    <span class="built_in">CFRelease</span>(path);</div><div class="line">    <span class="built_in">CFRelease</span>(framesetter);</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>下面总结一下CoreText的优缺点：</p>
<ul>
<li>优点：功能强大，支持iOS3.2以后的所有系统</li>
<li>缺点：纯C的接口，使用复杂，需要自己管理内存</li>
</ul>
<p>CoreText更加详细的介绍推荐大家可以看看唐巧大神的《iOS开发进阶》第十七章的内容。</p>

      
    </div>

    <div>
      
        
      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/10/04/iOS中的富文本技术(1)TextKit简介/" rel="next" title="iOS中的富文本技术(1)TextKit简介">
                <i class="fa fa-chevron-left"></i> iOS中的富文本技术(1)TextKit简介
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/10/04/iOS运行时初探-使用运行时机制向Category中添加属性/" rel="prev" title="iOS运行时初探 使用运行时机制向Category中添加属性">
                iOS运行时初探 使用运行时机制向Category中添加属性 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2015/10/04/iOS中的富文本技术(2)CoreText框架/"
           data-title="iOS中的富文本技术(2)CoreText框架" data-url="http://yoursite.com/2015/10/04/iOS中的富文本技术(2)CoreText框架/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/smallhead.png"
               alt="liujinlongxa" />
          <p class="site-author-name" itemprop="name">liujinlongxa</p>
          <p class="site-description motion-element" itemprop="description">生命永不息，Coding永不止</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">31</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/liujinlongxa" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/JaylonLiu" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1523828165/home" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/2470188/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  豆瓣
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">2.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#示例"><span class="nav-number">3.</span> <span class="nav-text">示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">liujinlongxa</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"liujinlongxa"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  






  
  
  

  

  

</body>
</html>
